import store from '@/store/'

export const WebsocketTableMixin = {
  mounted() {
    this.initWebSocket();
    this.heartCheckFun();
  },
  destroyed: function () {
    // 离开页面生命周期函数
    this.websocketOnclose();
  },
  methods:{
    initWebSocket: function () {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var userId = store.getters.userInfo.id;
      var url = window._CONFIG['domianURL'].replace("https://","wss://").replace("http://","ws://")+"/"+this.socketUrl+"/"+userId;
      // var url = "ws://localhost:8080"+"/jeecg-boot/websocket/"+ userId
      console.log(url);

      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketOnopen;
      this.websock.onerror = this.websocketOnerror;
      this.websock.onmessage = this.websocketOnmessage;
      this.websock.onclose = this.websocketOnclose;
    },
    websocketOnopen: function () {
      console.log("WebSocket连接成功");
      this.initTable()
      //心跳检测重置
      this.heartCheck.reset().start();
    },
    websocketOnerror: function (e) {
      console.log("WebSocket连接发生错误");
      this.reconnect();
    },
    websocketOnmessage(e) {
      // console.log("-----接收消息-------",e.data);
      let result = JSON.parse(e.data)
      // console.log(result.current)
      this.dataSource = result.records
      this.pagination.current = result.current
      this.pagination.pageSize = result.size
      this.pagination.total = result.total
      this.heartCheck.reset().start();
    },
    websocketOnclose: function (e) {
      console.log("connection closed (" + e + ")");
      if(e){
        console.log("connection closed (" + e.code + ")");
      }
      this.reconnect();
    },
    websocketSend(text) { // 数据发送
      console.log(text)
      try {
        this.websock.send(text);
      } catch (err) {
        console.log("send failed (" + err + ")");
        console.log("send failed (" + err.code + ")");
      }
    },
    reconnect() {
      var that = this;
      if(that.lockReconnect) return;
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info("尝试重连...");
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    },
    heartCheckFun(){
      let that = this;
      //心跳检测,每20s心跳一次
      that.heartCheck = {
        timeout: 20000,
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function(){
          clearTimeout(this.timeoutObj);
          //clearTimeout(this.serverTimeoutObj);
          return this;
        },
        start: function(){
          let self = this;
          this.timeoutObj = setTimeout(function(){
            // 刷新页面
            that.websocketSend(JSON.stringify(that.pagination))
          }, this.timeout)
        }
      }
    }
  }

}